/*
four scroll view controllers:
 documents_min_MySavedFiles_ScrollViewController
 documents_max_MySavedFiles_ScrollViewController
 documents_max_Community_ScrollViewController
 documents_max_Search_ScrollViewController
    -scroll event
    -simple and separate operations

one export scroll view class:
 Export_CommunityDocs_ScrollViewController:
 -export for community window

one total controller:
 documents_controller
    -manage scroll controllers
    -ui callbacks(button clicked)
    -control and update ui
    -some process functions
    -request networks and callbacks

one model:
 documents_view_model
    -all parameters for network protocol(api).
    -all data received.
    -all networks.
    -page display status
    -other data
*/
var useragent = Workport.getBrowser();
var documents_min_MySavedFiles_ScrollViewController = (function () {
    var next = true;
    var container = $('#documents_body_min');
    var pageTmpl = $('#documents_panel_min_my_saved_files_div');
    var tableTmpl = $('#documents_panel_min_table');
    var rowTmpl = $('#documents_panel_min_my_saved_files');
    var height = Screen.bodyHeight-50;
    var loaderDefOptions = {imgColor:'black', textCSS:{'color':'black'}};
    var documents_panel = $('#documents_panel');
    var loader = new Workport.Loader(documents_panel, loaderDefOptions);
    return {
        loader:loader,
        setLoader:function(_loader){
            this.loader = _loader || loader;
        },
        resetLoader:function(){
            return this.loader = loader;
        },
        init : function () {
            var self = this;
            pageTmpl.appendTo(container);
            if(useragent == 'ipad'){
                $('#documents_panel_min_my_saved_files_div').css('overflow-x','hidden');
                $('#documents_panel_min_my_saved_files_div').css('overflow-y','scroll');
                $('#documents_panel_min_my_saved_files_div').css('height',height);
                $('#documents_panel_min_my_saved_files_div').css('width','256px');

                $("#documents_panel_min_my_saved_files_div").bind("scroll",function(){
                    if($("#documents_panel_min_my_saved_files_div")[0].scrollTop == 0){ //top
                         // self.refreshAll();
                    } else if($("#documents_panel_min_my_saved_files_div")[0].scrollHeight <= $("#documents_panel_min_my_saved_files_div")[0].scrollTop + $("#documents_panel_min_my_saved_files_div").height()){ // bottom
                         self.appendToBottom();
                    }
                });
            } else {
                pageTmpl.slimScroll({
                    wheelStep : 20,
                    height : height,
                    allowPageScroll : true,
                    width: 256,
                    start : 'top',
                    touchScrollStep : 200,
                    disableFadeOut:true
                });
                pageTmpl.slimScroll().bind('slimscroll', function(e, pos){
                    if (documents_view_model.status_min_display) {
                        if (pos == 'bottom') {
                            self.appendToBottom();
                        } else if (pos == 'top') {
                           // self.insertToTop();
                           // self.refreshAll();
                        }
                    }
                });
            }
            container.css({height : height});
            documents_view_model.documents_min_mysavedfile_index = Letter(container, function(element) {
                documents_view_model.parameterForMySavedFiles.key = element;
                if (element == 'All') {
                    documents_view_model.parameterForMySavedFiles.key = '';
                } else if (element == '#') {
                    documents_view_model.parameterForMySavedFiles.key = 'others';
                }
                $("#documents_body_min").show();
                $("#documents_body_max_search").hide();
                self.refreshAll();
            }, '#cccccc');
            container.css({height : height});
            if(useragent == 'ipad'){
                $('#documents_min_alpa_index_letter').css('top','47px');
            }
        },
        appendToBottom : function () {
            if (!next) {
                return;
            }
            var self = this;
            loader.setOptions({text:'',position:'down',imgColor:'black'});
            loader.show();
            var callback = function (deltaData) {
                self.render(deltaData, true);
            };
            if (documents_view_model.request_MySavedFiles(1, callback, pageTmpl.scrollTop())) {
                next = false;
            }
        },
        insertToTop : function () {
            if (!next) {
                return;
            }
            var self = this;
            loader.setOptions({text:'',position:'up',imgColor:'black',imgCSS:{'margin-top':'50px'}});
            loader.show();
            var callback = function (deltaData) {
                self.render(deltaData, false);
            };
            if (documents_view_model.request_MySavedFiles(-1, callback, pageTmpl.scrollTop())) {
                next = false;
            }
        },
        refreshAll : function () {
            if (!next) {
                return;
            }
            var self = this;
            loader.setOptions(loaderDefOptions);
            loader.show();
            tableTmpl.off("*");
            tableTmpl.empty();
            var callback = function (deltaData) {
                self.render(deltaData, true);
                loader.hide();
            };
            if (documents_view_model.request_MySavedFiles(0, callback, 0)) {
                next = false;
            }
        },
        render : function (deltaData, isAppendToBottom) {
            if (!deltaData || deltaData.length == 0||deltaData==null) {
                next = true;
                //check if it is the very first time..if no result show a tooltip.
                var isDataEmpty = !documents_view_model.data_MySavedFiles.data || documents_view_model.data_MySavedFiles.data.length == 0;
                var isNoKey = !documents_view_model.parameterForMySavedFiles.key || documents_view_model.parameterForMySavedFiles.key == '';
                var isOffsetNull = !documents_view_model.parameterForMySavedFiles.offset || documents_view_model.parameterForMySavedFiles.offset == "''";
                if (isDataEmpty && isNoKey && isOffsetNull) {
                    $('#documents_first_time_tooltip').show();
                    setTimeout(function(){
                        $('#documents_first_time_tooltip').hide();
                    },2000);
                } else {
                    //check if it is no result for search
                    $('#documents_first_time_tooltip').hide();
                    var key = jQuery.parseJSON(documents_view_model.requestArray[0]).key;
                    key = key == 'others' ? '#': key;
                    tableTmpl.html(kendo.template($('#documents_noresult_template').html())({grouptype:'Documents',keyword:key}));
                }
                return;
            }else{
                $('#documents_first_time_tooltip').hide();
            }
            var tmpl = kendo.template(rowTmpl.html());
            var result = tmpl(deltaData);
            if (isAppendToBottom) {
                tableTmpl.append(result);
            } else {
                tableTmpl.html(result + tableTmpl.html())
            }
            if(useragent !='ipad'){
               pageTmpl.slimScroll({});
            }
            next = true;
        }
    }
})();

var documents_max_MySavedFiles_ScrollViewController = (function () {
    var next = true;
    var container = $('#documents_body_max_my_saved_files');
    var pageTmpl = $('#documents_panel_max_my_saved_files_div');
    var tableTmpl = $('#documents_panel_max_table');
    var rowTmpl = $('#documents_panel_max_my_saved_files');
    var height = Screen.bodyHeight-50;
    var loaderDefOptions = {imgColor:'black', textCSS:{'color':'black'}};
    return {
        tableTmpl:tableTmpl,
        loader:documents_min_MySavedFiles_ScrollViewController.loader,
        init : function () {
            var self = this;
            pageTmpl.appendTo(container);
            if(useragent == 'ipad'){
                $('#documents_panel_max_my_saved_files_div').css('overflow-x','hidden');
                $('#documents_panel_max_my_saved_files_div').css('overflow-y','scroll');
                $('#documents_panel_max_my_saved_files_div').css('height',height);
                $('#documents_panel_max_my_saved_files_div').css('width','743px');
                $("#documents_panel_max_my_saved_files_div").bind("scroll",function(){
                    if($("#documents_panel_max_my_saved_files_div")[0].scrollTop == 0){ //top
                        // self.refreshAll();
                    } else if($("#documents_panel_max_my_saved_files_div")[0].scrollHeight <= $("#documents_panel_max_my_saved_files_div")[0].scrollTop + $("#documents_panel_max_my_saved_files_div").height()){ // bottom
                        self.appendToBottom();
                    }
                });
            } else {
                pageTmpl.slimScroll({
                    wheelStep : 20,
                    height : height,
                    allowPageScroll : true,
                    width: 743,
                    start : 'top',
                    touchScrollStep : 200,
                    disableFadeOut:true
                });
                pageTmpl.slimScroll().bind('slimscroll', function(e, pos){
                    if (!documents_view_model.status_min_display) {
                        if (pos == 'bottom') {
                            self.appendToBottom();
                        } else if (pos == 'top') {
                            //self.insertToTop();
                            // self.refreshAll();
                        }
                    }
                });
            }
            container.css({height : height});
            documents_view_model.documents_max_mysavedfile_index = Letter(container, function(element) {
                documents_view_model.parameterForMySavedFiles.key = element;
                if (element == 'All') {
                    documents_view_model.parameterForMySavedFiles.key = '';
                } else if (element == '#') {
                    documents_view_model.parameterForMySavedFiles.key = 'others';
                }
                $("#documents_body_max").show();
                $("#documents_body_max_search").hide();
                self.refreshAll();
            }, '#cccccc');
            container.css({height : height});
           if(useragent == 'ipad'){
             $('#documents_max_my_alph_index_letter').css('top','47px');
           }
        },
        appendToBottom : function () {
            if (!next) {
                return;
            }
            var self = this;
            this.loader.setOptions($.extend(true,{},loaderDefOptions,{text:'',position:'down'}));
            this.loader.show();
            var callback = function (deltaData) {
                self.render(deltaData, true);
            };
            if (documents_view_model.request_MySavedFiles(1, callback, pageTmpl.scrollTop())) {
                next = false;
            }
        },
        insertToTop : function () {
            if (!next) {
                return;
            }
            var self = this;
            this.loader.setOptions($.extend(true,{},loaderDefOptions,{text:'',position:'up'}));
            this.loader.show();
            var callback = function (deltaData) {
                self.render(deltaData, false);
            };
            if (documents_view_model.request_MySavedFiles(-1, callback, pageTmpl.scrollTop())) {
                next = false;
            }
        },
        refreshAll : function () {
            if (!next) {
                return;
            }
            var self = this;
            this.loader.setOptions(loaderDefOptions);
            this.loader.show();
            tableTmpl.off("*");
            tableTmpl.empty();
            var callback = function (deltaData) {
                self.render(deltaData, true);
                self.loader.hide();
            };
            if (documents_view_model.request_MySavedFiles(0, callback, 0)) {
                next = false;
            }
        },
        render : function (deltaData, isAppendToBottom) {
            //documents_view_model.documents_full_screen_loading_layer.hide();
            /*if (!deltaData) {
                next = true;
                //check if it is no result for search
                if (!documents_view_model.data_MySavedFiles.data || documents_view_model.data_MySavedFiles.data.length <= 0) {
                    tableTmpl.html(kendo.template($('#documents_noresult_template').html()));
                }
                return;
            }*/
            if (!deltaData || deltaData.length == 0||deltaData==null) {
                next = true;
                //check if it is no result for search
                if (!documents_view_model.data_MySavedFiles.data || documents_view_model.data_MySavedFiles.data.length <= 0) {
                    $('#documents_first_time_tooltip').hide();
                    var key = jQuery.parseJSON(documents_view_model.requestArray[0]).key;
                    key = key == 'others' ? '#': key;
                    tableTmpl.html(kendo.template($('#documents_noresult_template').html())({grouptype:'Documents',keyword:key}));
                }
                return;
            }
            else{
                $('#documents_first_time_tooltip').hide();
            }

            var tmpl = kendo.template(rowTmpl.html());
            var result = tmpl(deltaData);
            if (isAppendToBottom) {
                tableTmpl.append(result);
            } else {
                tableTmpl.html(result + tableTmpl.html())
            }
            if(useragent !='ipad'){
                pageTmpl.slimScroll({});
            }
            next = true;
        }
    }
})();

var documents_max_Community_ScrollViewController = (function () {
    var next = true;
    var container = $('#documents_body_max_communities');
    var pageTmpl = $('#documents_panel_max_communities_div');
    var tableTmpl = $('#documents_panel_max_communities_list');
    var rowTmpl = $('#documents_panel_max_communities');
    var height = Screen.bodyHeight-50;
    var loaderDefOptions = {imgColor:'black', textCSS:{'color':'black'}};
    return {
        loader:documents_min_MySavedFiles_ScrollViewController.loader,
        init : function () {
            var self = this;
            pageTmpl.appendTo(container);
            if(useragent == 'ipad'){
                $('#documents_panel_max_communities_div').css('overflow-x','hidden');
                $('#documents_panel_max_communities_div').css('overflow-y','scroll');
                $('#documents_panel_max_communities_div').css('height',height);
                $('#documents_panel_max_communities_div').css('width','743px');
                $("#documents_panel_max_communities_div").bind("scroll",function(){
                    if($("#documents_panel_max_communities_div")[0].scrollTop == 0){ //top
                        //self.refreshAll();
                    } else if($("#documents_panel_max_communities_div")[0].scrollHeight <= $("#documents_panel_max_communities_div")[0].scrollTop + $("#documents_panel_max_communities_div").height()){ // bottom
                        self.appendToBottom();
                    }
                });
            } else{
                pageTmpl.slimScroll({
                    wheelStep : 20,
                    height : height,
                    allowPageScroll : true,
                    width: 743,
                    start : 'top',
                    touchScrollStep : 200,
                    disableFadeOut:true
                });
                pageTmpl.css({width : '720px'});
                pageTmpl.slimScroll().bind('slimscroll', function(e, pos){
                    if (!documents_view_model.status_min_display) {
                        if (pos == 'bottom') {
                            self.appendToBottom();
                        } else if (pos == 'top') {
    //                        self.insertToTop();
    //                        self.refreshAll();
                        }
                    }
                });
            }
            container.css({height : height});
            documents_view_model.documents_max_community_index = Letter(container, function(element) {
                documents_view_model.parameterForMashedUpCommunitiesAndFiles.key = element;
                if (element == 'All') {
                    documents_view_model.parameterForMashedUpCommunitiesAndFiles.key = '';
                } else if (element == '#') {
                    documents_view_model.parameterForMashedUpCommunitiesAndFiles.key = 'others';
                }
                $("#documents_body_max").show();
                $("#documents_body_max_search").hide();
                self.refreshAll();
            }, '#cccccc');
            container.css({height : height});
            if(useragent == 'ipad'){
                $('#documents_max_my_alph_index_letter').css('top','47px');
            }
        },
        appendToBottom : function () {
            if (!next) {
                return;
            }
            var self = this;
            var callback = function (deltaData) {
                self.render(deltaData, true);
                self.loader.hide();
            };
            this.loader.setOptions($.extend(true,{},loaderDefOptions,{text:'',position:'down'}));
            this.loader.show();
            if (documents_view_model.request_MashedUpCommunitiesAndFiles(1, callback, pageTmpl.scrollTop())) {
                next = false;
            }
        },
        insertToTop : function () {
            if (!next) {
                return;
            }
            var self = this;
            this.loader.setOptions($.extend(true,{},loaderDefOptions,{text:'',position:'up'}));
            this.loader.show();
            var callback = function (deltaData) {
                self.render(deltaData, false);
                self.loader.hide();
            };
            if (documents_view_model.request_MashedUpCommunitiesAndFiles(-1, callback, pageTmpl.scrollTop())) {
                next = false;
            }
        },
        refreshAll : function () {
            if (!next) {
                return;
            }
            var self = this;
            this.loader.setOptions(loaderDefOptions);
            this.loader.show();
            documents_max_MySavedFiles_ScrollViewController.tableTmpl.off("*").empty();
            tableTmpl.off("*").empty();
            var callback = function (deltaData) {
                self.loader.hide();
                self.render(deltaData, true);
            };
            if (documents_view_model.request_MashedUpCommunitiesAndFiles(0, callback, 0)) {
                next = false;
            }
        },
        viewMore : function(element, communityID) {
            var viewMoreTargetElement = $('#documents_max_communities_list_' + communityID),
                self = this;
            if (viewMoreTargetElement != undefined) {
                this.loader.setOptions($.extend(true,{},loaderDefOptions,{boxCSS:{opacity:1}}));
                this.loader.show();
                var callback = function (deltaData) {
                    self.loader.hide();
                    var targetCommunity;
                    var template = kendo.template($('#documents_panel_max_communities_table_documents_body').html());
                    for (var i = 0; i < documents_view_model.data_CommunitiesFiles.data.length; i++) {
                        var comID = documents_view_model.data_CommunitiesFiles.data[i].CommunityId;
                        if (comID == communityID) {
                            targetCommunity = documents_view_model.data_CommunitiesFiles.data[i];
                            //update html with new data and template
                            var data = {data: documents_view_model.data_CommunitiesFiles.data[i]};
                            var result = template(data);
                            viewMoreTargetElement.html(result);
                            //update the view(height).
                            var count = targetCommunity.FileBasicDetails.length;
                            if (parseInt(targetCommunity.TotalFileCount) <= targetCommunity.FileBasicDetails.length) {
//                                count = parseInt(targetCommunity.TotalFileCount);//server bug the result may more than the totalfilecount
                                $('#documents_view_more_' + communityID).hide();
                            } else if (targetCommunity.respCode == 'WP1005') {
                                $('#documents_view_more_' + communityID).hide();
                            }
                            if (count > 4) {
                                $('#documents_retract_' + communityID).show();
                            }
                            var targetHeight = (parseInt((count - 1) / 4) + 1) * (60 + 2);
                            viewMoreTargetElement.animate({height: targetHeight + 'px'}, 0);
                            viewMoreTargetElement.parent().animate({height: targetHeight + 5 + 'px'}, 0);
                            viewMoreTargetElement.find('.documents_pane_max_list_item_not_first').show();
                            break;
                        }
                    }
                };
                if ($(element).parent().find('.documents_retract')[0].style.display == 'none') {
                    documents_view_model.request_CommunityDocs(communityID, false, callback);
                } else {
                    documents_view_model.request_CommunityDocs(communityID, true, callback);
                }
            }
        },
        retract : function(element, communityID){
            var communityTable = $('#' + communityID);
            var targetElement = communityTable;
            if (targetElement != undefined) {
                communityTable.find('.documents_pane_max_list_item_not_first').hide();
                targetElement.animate({height:"60px"},300);
                targetElement.parent().animate({height:"65px"},300);
                $(element).hide();
                $(element).parent().find('.documents_view_more').show();
            }
        },
        render : function (deltaData, isAppendToBottom) {
            //documents_view_model.documents_full_screen_loading_layer.hide();
            if (!deltaData) {
                next = true;
                //check if it is no result for search
                if (!documents_view_model.data_CommunitiesFiles.data || documents_view_model.data_CommunitiesFiles.data.length <= 0) {
                    var key = jQuery.parseJSON(documents_view_model.requestArray[0]).key;
                    key = key == 'others' ? '#': key;
                    tableTmpl.html(kendo.template($('#documents_noresult_template').html())({grouptype:'Communities',keyword:key}));
                }
                return;
            }
            var tmpl = kendo.template(rowTmpl.html());
            var result = tmpl(deltaData);
            if (isAppendToBottom) {
                tableTmpl.append(result);
            } else {
                tableTmpl.html(result + tableTmpl.html())
            }
            //for the docs
            var docTemplate = kendo.template($('#documents_panel_max_communities_table_documents_body').html());
            for (var i = 0; i < deltaData.length; i ++) {
                var comID = deltaData[i].CommunityId;
                var docData = {data : deltaData[i]};
                var docResult = docTemplate(docData);
                $('#documents_max_communities_list_'+comID).html(docResult);
            }
            if(useragent != 'ipad'){
                pageTmpl.slimScroll({});
            }
            next = true;
        }
    }
})();

var documents_max_Search_ScrollViewController = (function () {
    var next = true;
    var pageTmpl = $('#documents_search_result_table_div');
    var tableTmpl = $('#documents_search_result_table');
    var rowTmpl = $('#documents_panel_max_search_table_content');
    var height = Screen.bodyHeight-60-50;
    var loaderDefOptions = {imgColor:'black', textCSS:{'color':'black'}};
    return {
        loader:documents_min_MySavedFiles_ScrollViewController.loader,
        init : function () {
            var self = this;
            $("#documents_panel_max_search").appendTo($('#documents_body_max_search'));
            if(useragent == 'ipad'){
                $("#documents_search_result_table_div").appendTo($('#documents_search_result_table_div'));
                $('#documents_search_result_table_div').css('overflow-x','hidden');
                $('#documents_search_result_table_div').css('overflow-y','scroll');
                $('#documents_search_result_table_div').css('height',height);
                $("#documents_search_result_table_div").bind("scroll",function(){
                    if($("#documents_search_result_table_div")[0].scrollTop == 0){ //top
                        self.refreshAll();
                    } else if($("#documents_search_result_table_div")[0].scrollHeight <= $("#documents_search_result_table_div")[0].scrollTop + $("#documents_search_result_table_div").height()){ // bottom
                        self.appendToBottom();
                    }
                });
            } else{
                pageTmpl.slimScroll({
                    wheelStep : 20,
                    width : 768,
                    height : height,
                    start : 'top',
                    touchScrollStep : 200,
                    disableFadeOut:true
                });
                pageTmpl.slimScroll().bind('slimscroll', function(e, pos){
                    if (!documents_view_model.status_min_display) {
                        if (pos == 'bottom') {
                            self.appendToBottom();
                        }
                    }
                });
            }
            pageTmpl.hide();
        },
        reinit : function () {
            $('#documents_panel_max_search').find('div.slimScrollDiv').hide();
            documents_view_model.search_result.keyword = '';
            documents_view_model.search_result.data.length = 0;
            if (documents_view_model.status_max_panel_index == 0) {
                documents_view_model.parameterForSearch.entity = 'U';
            } else if (documents_view_model.status_max_panel_index == 1) {
                documents_view_model.parameterForSearch.entity = 'C';
            }
            this.updateMenuTable();
            $('#documents_search_keywords').val('');
            tableTmpl.off("*");
            tableTmpl.empty();
        },
        appendToBottom : function () {
            if (!next) {
                return;
            }
            var self = this;
            this.loader.setOptions($.extend({},loaderDefOptions,{text:'',position:'down'})).show();
            this.loader.show();
            var callback = function (deltaData) {
                self.render(deltaData, true);
                self.loader.hide();
            };
            if (documents_view_model.request_Search(true,'', callback, pageTmpl.scrollTop())) {
                next = false;
            }
        },
        updateMenuTable : function () {
            var menu = $('#documents_search_menu');
            menu.off("*");
            menu.empty();
            var tmpl = kendo.template($('#documents_panel_max_search_table').html());
            var result = tmpl(documents_view_model.search_result);
            menu.html(result);
        },
        doSearch : function () {
            var self = this;
            var searchBar = $('#documents_search_keywords');
            var keyword = searchBar.val();
            if($.trim(keyword) == "") {
                searchBar.kendoTooltip({
                    content: 'Please input the keywords.',
                    position: "right",
                    showOn: false
                });
                searchBar.data('kendoTooltip').show();
                return;
            }
            tableTmpl.off("*").empty();
            $("#documents_body_max").hide();
            $("#documents_body_max_search").show();
            this.loader.setOptions(loaderDefOptions).show();
            var callback = function (deltaData) {
                self.loader.hide();
                pageTmpl.show();
                self.render(deltaData, true);
                $('#documents_search_keywords').val(keyword);
            };
            documents_view_model.request_Search(false,keyword,callback,pageTmpl.scrollTop())
        },
        render : function (deltaData, isAppendToBottom) {
            if (!deltaData) {
                next = true;
                deltaData = [];
                deltaData.keyword = documents_view_model.search_result.keyword;
            }
            this.updateMenuTable();
            $('#documents_panel_max_search').find('div.slimScrollDiv').show();
            var tmpl = kendo.template(rowTmpl.html());
            deltaData.renderType = documents_view_model.status_max_panel_index;
            var result = tmpl(deltaData);
            if (isAppendToBottom) {
                tableTmpl.append(result);
            } else {
                tableTmpl.html(result + tableTmpl.html())
            }
            if (deltaData.keyword) {
                $('.documents_search_content>.documents_panel_list_item_four_title').highlight(deltaData.keyword);
            }
            if(useragent != 'ipad'){
                pageTmpl.slimScroll({});
            }
            next = true;
        }
    }
})();

var Export_CommunityDocs_ScrollViewController = function (containerElement, communityId) {
    var next = true;
    var container = containerElement;
    container.html('<div class="export_documents_communitydocs_page wp_ml_25 wp_mt_15">' +
        '<table class="wp_mt_1 export_documents_communitydocs_table" style="width: 720px;"></table>'+
        '</div>');
    var pageTmpl = $(container.find('.export_documents_communitydocs_page')[0]);
    var tableTmpl = $(container.find('.export_documents_communitydocs_table')[0]);
    var rowTmpl = $('#documents_panel_max_my_saved_files');
    var height = container.css('height');
    var offset = '';
    var comID = communityId;
    var timeOrder = true;
    var nameOrder = true;
    var filter = '';
    var order = '';
    var self;
        pageTmpl.slimScroll({
        wheelStep : 20,
        height : 560,
        allowPageScroll : true,
        width: 743,
        start : 'top',
        touchScrollStep : 200,
        disableFadeOut:true
    });
    pageTmpl.slimScroll().bind('slimscroll', function(e, pos){
        if (pos == 'bottom') {
            self.appendToBottom();
        } else if (pos == 'top') {

        }
    });
    function render(deltaData, isAppendToBottom) {
        if (!deltaData) {
            next = true;
            //check if it is no result for search
            if (false) {
                var key = jQuery.parseJSON(documents_view_model.requestArray[0]).key;
                key = key == 'others' ? '#': key;
                tableTmpl.html(kendo.template($('#documents_noresult_template').html())({grouptype:'Communities',keyword:key}));
            }
            return;
        }
        deltaData.Export = true;
        var tmpl = kendo.template(rowTmpl.html());
        var result = tmpl(deltaData);
        if (isAppendToBottom) {
            tableTmpl.append(result);
        } else {
            tableTmpl.html(result + tableTmpl.html())
        }
        if(useragent != 'ipad'){
             pageTmpl.slimScroll({});
        }

        next = true;
    };
    var loaderDefOptions = {imgColor:'black', textCSS:{'color':'black'}};
    return {
        loader:documents_min_MySavedFiles_ScrollViewController.loader,
        init : function () {
            self = this;
        },
        setLoader:function(_loader){
            documents_min_MySavedFiles_ScrollViewController.setLoader(_loader);
        },
        resetLoader:function(){
            documents_min_MySavedFiles_ScrollViewController.resetLoader();
        },
        refreshAll : function () {
            var offset = '';
            var self = this;
            this.loader.setOptions(loaderDefOptions);
            this.loader.show();
            Workport.DocumentAPI.getCommunity(function (deltaData) {
                self.loader.hide();
                next = true;
                tableTmpl.off("*").empty();
                documents_max_MySavedFiles_ScrollViewController.tableTmpl.off("*").empty();
                if (!deltaData) {
                    return;
                }
                if (!deltaData.FileBasicDetails) {
                    tableTmpl.html('<p style="width: 700px;text-align: center;color: #595959;">There are no documents in the community.</p>');
                    return;
                }
                var last = deltaData.FileBasicDetails.length-1;
                if (last > 0) {
                    offset = deltaData.FileBasicDetails[last].LastModifiedDate;
                }
                render(deltaData.FileBasicDetails, true);
                if ( deltaData.ResponseCode == 'WP1005') {
                    next = false;
                }
            },{
                communityId : comID,
                pageSize : 36,
                offset : offset,//(Lastmodifieddate of the last record),
                filter : filter,
                order : order
            });
        },
        appendToBottom : function () {
            if (!next) {
                return;
            }
            Workport.DocumentAPI.getCommunity(function (deltaData) {
                next = true;
                if (!deltaData) {
                    return;
                }
                if (!deltaData.FileBasicDetails) {
                    Workport.utils.alertMsg("", deltaData.ResponseMessage, function(_data){});
                    return;
                }
                var last = deltaData.FileBasicDetails.length-1;
                if (last > 0) {
                    offset = deltaData.FileBasicDetails[last].LastModifiedDate;
                }
                render(deltaData.FileBasicDetails, true);
                if ( deltaData.ResponseCode == 'WP1005') {
                    next = false;
                }
            },{
                communityId : comID,
                pageSize : 36,
                offset : offset,//(Lastmodifieddate of the last record),
                filter : filter,
                order : order
            });
            next = false;
        },
        orderByTime : function () {
            timeOrder = !timeOrder;
            filter =  'Time';
            order = timeOrder ? 'false' : 'true';
            this.refreshAll();
            return timeOrder;
        },
        orderByName : function () {
            nameOrder = !nameOrder;
            filter = 'Name';
            order = nameOrder ? "true" : 'false';
            this.refreshAll();
            return nameOrder;
        }
    }
};

var documents_controller = (function(){
    var loaderDefOptions = {imgColor:'black', textCSS:{'color':'black'}};
    var loader = new Workport.Loader($("#documents_community_details_windows"),loaderDefOptions);
    var FLAG = false;
    return {
        FLAG:FLAG,
        loader:loader,
        init : function () {
            //init scroll view controllers
            documents_min_MySavedFiles_ScrollViewController.init();
            documents_max_MySavedFiles_ScrollViewController.init();
            documents_max_Community_ScrollViewController.init();
            documents_max_Search_ScrollViewController.init();
            //community detail window
            {
                var documents_community_detail_win = $("#documents_community_details_windows");
                documents_view_model.documents_community_detail_win = documents_community_detail_win;
                documents_community_detail_win.kendoWindow({
                    width: 658,
                    height: 640,
                    title: 'Community Profile',
                    visible: false,
                    draggable: false,
                    resizable: false,
                    actions: ["Close"],
                    modal: true,
                    close: function () {
                        if(useragent == 'ipad'){
                            $('body').unbind('touchmove');
                            $('#communities_profile').unbind('touchmove');
                        }
                    },
                    open:function(){
                        if(useragent == 'ipad'){
                            $('body').bind('touchmove',function(event){event.preventDefault()});
                            $('#communities_profile').bind('touchmove',function(event){event.stopPropagation()});
                        }
                    }
                });
                kendo.bind(documents_community_detail_win, documents_view_model);
            }

            //document details window
            {
                var documents_document_detail_win = $('#documents_document_details_windows');
                documents_document_detail_win.css('min-height','100px');
                documents_view_model.documents_document_detail_win = documents_document_detail_win;
                documents_document_detail_win.kendoWindow({
                    width: 256,
                    height: 'auto',
                    title: 'Properties',
                    visible: false,
                    draggable: false,
                    modal: true,
                    resizable: false,
                    actions: ["Close"],
                    open:function(){
                        loader.setContent(documents_document_detail_win,loaderDefOptions);
                        loader.show();
                        if(useragent == 'ipad'){
                            $('body').bind('touchmove',function(event){event.preventDefault()});
                            documents_document_detail_win.bind('touchmove',function(event){event.stopPropagation()});
                        }
                    },
                    close:function(){
                        loader.hide();
                        if(useragent == 'ipad'){
                            $('body').unbind('touchmove');
                            documents_document_detail_win.unbind('touchmove');
                        }
                    }
                });
                kendo.bind($("#documents_document_details_windows"), documents_view_model);
            }

            //version history window
            {
                var documents_version_detail_win = $('#documents_document_version_details_window');
                documents_view_model.documents_version_detail_win = documents_version_detail_win;
                documents_version_detail_win.kendoWindow({
                    width: 256,
                    height: 'auto',
                    maxHeight: 235,
                    title: 'Version History',
                    visible: false,
                    draggable: false,
                    modal: true,
                    resizable: false,
                    actions: ["Close"],
                    open:function(e){
                        loader.setContent(documents_version_detail_win,loaderDefOptions);
                        loader.show();
                    },
                    close:function(){
                        loader.hide();
                    }
                });
                kendo.bind(documents_version_detail_win, documents_view_model);
                documents_version_detail_win.slimScroll({
                    wheelStep: 20,
                    height: 235,
                    allowPageScroll: true,
                    disableFadeOut:true
                });
            }

            //check in window
            {
                var documents_checkin_win = $('#documents_document_checkin_window');
                documents_view_model.documents_checkin_win = documents_checkin_win;
                documents_checkin_win.kendoWindow({
                    width: 256,
                    height: 200,
                    title: 'Check-in',
                    modal: true,
                    visible: false,
                    draggable: false,
                    resizable: false,
                    actions: ["Close"],
                    close : function () {
                        $('#documents_select_file_name').val('');
                        $('#documents_select_file_remarks').val('');
                    }
                });
            }

            //copy to window
            {
                var documents_copy_win = $('#documents_document_copy_window');
                documents_view_model.documents_copy_win = documents_copy_win;
                documents_copy_win.kendoWindow({
                    width: 256,
                    height: 180,
                    title: 'Copy',
                    visible: false,
                    draggable: false,
                    modal: true,
                    resizable: false,
                    actions: ["Close"],
                    open:function(){
                        loader.setContent(documents_copy_win).setOptions(loaderDefOptions);
                        loader.show();
                    },
                    close:function(){
                        loader.hide();
                    }
                });
                $('#documents_copy_window_candidate_area').slimScroll({
                    wheelStep: 20,
                    height: 110,
                    width: 200,
                    disableFadeOut:true
                });
            }

            //documents_view_model.documents_full_screen_loading_layer = $('#documents_panel_full_screen_loading');

            kendo.bind("#documents_panel", documents_view_model);
            //load min panel
            documents_controller.load_page();
            documents_min_MySavedFiles_ScrollViewController.refreshAll();
        },
        zoomin_callback : function() {
            $('#documents_panel').css({width:"768"});
            $('#documents_first_time_tooltip').hide();
            documents_controller.load_maxpage();
            $("#documents_panel_resize_icon").toggleClass("main_common_f_13_13 main_common_m_13_13");

            documents_view_model.documents_max_mysavedfile_index.cancleHighLight();
            documents_view_model.documents_max_community_index.cancleHighLight();
            documents_view_model.parameterForMySavedFiles.key = null;
            documents_view_model.parameterForMashedUpCommunitiesAndFiles.key = null;
            documents_view_model.status_min_display = false;
            if (documents_view_model.status_max_panel_index == 0) {
                documents_max_MySavedFiles_ScrollViewController.refreshAll();
            } else if (documents_view_model.status_max_panel_index == 1) {
                documents_max_Community_ScrollViewController.refreshAll();
            }
            documents_view_model.documents_max_mysavedfile_index.update();
            documents_view_model.documents_max_community_index.update();
        },
        zoomout_callback : function(){
            $('#documents_panel').css({width:"256"});
            documents_controller.load_minpage();
            $("#documents_panel_resize_icon").toggleClass("main_common_f_13_13 main_common_m_13_13");

            documents_view_model.documents_min_mysavedfile_index.cancleHighLight();
            documents_view_model.parameterForMySavedFiles.key = null;
            documents_view_model.status_min_display = true;
            documents_min_MySavedFiles_ScrollViewController.refreshAll();
            documents_view_model.documents_min_mysavedfile_index.update();
        },
        load_page : function () {
            $("#documents_menubar_min_list").kendoMenu({select: documents_controller.onMinMenuClicked});
            $("#documents_menubar_max_list").kendoMenu({select: documents_controller.onMaxMenuClicked});

            // $('#documents_panel').appendTo();
            $('#documents').html($('#documents_panel'));
            $('#documents_menu_min').hide();
            $('#documents_menu_max').hide();
            $('#documents_body_min').hide();
            $('#documents_body_max').hide();
        },
        load_minpage : function () {
            $('#documents_menu_min').show();
            $('#documents_menu_max').hide();
            $('#documents_body_min').show();
            $('#documents_body_max').hide();
            $('#documents_body_max_search').hide();
        },
        load_maxpage : function (){
            $('#documents_menu_min').hide();
            $('#documents_menu_max').show();
            $('#documents_body_min').hide();
            $('#documents_body_max').show();
            $('#documents_body_max_search').hide();
        },
        onMinMenuClicked : function(e) {
            return;
            var selectedItemText = e.item.textContent;
            if (selectedItemText != undefined) {
                var index = $.inArray(selectedItemText, documents_view_model.menuItems.data);
                if (index != -1) {
                    var item = $("#documents_menubar_min_selected_item");
                    item[0].textContent = selectedItemText;
                }
            }
        },
        onMaxMenuClicked : function(e) {
            var selectedItemText = e.item.textContent;
            if (selectedItemText != undefined) {
                var index = $.inArray(selectedItemText, documents_view_model.menuItems.data);
                if (index != -1) {
                    //highlight the selected menu item
                    for (var i = 0; i < documents_view_model.menuItems.data.length; i ++) {
                        var itemIdName = "#documents_menubar_max_list_item" + i;
                        if (i == index) {
                            $(itemIdName).css({
                                "background-color" : "#CCCCCC"
                            });
                        } else {
                            $(itemIdName).css({
                                "background-color" : "#7BD94C"
                            });
                        }
                    }
                    //show the selected list, hide the others
                    documents_view_model.documents_max_mysavedfile_index.cancleHighLight();
                    documents_view_model.documents_max_community_index.cancleHighLight();
                    documents_view_model.documents_min_mysavedfile_index.cancleHighLight();
                    var max_my = $("#documents_body_max_my_saved_files");
                    var max_com = $("#documents_body_max_communities");
                    var max_lib = $("#documents_body_max_libraty_tools");
                    $("#documents_body_max").show();
                    max_my.hide();
                    max_com.hide();
                    max_lib.hide();
                    $("#documents_body_max_search").hide();

                    documents_view_model.status_max_panel_index = index;
                    switch (index) {
                        case 0:
                            documents_view_model.parameterForMySavedFiles.key = null;
                            documents_max_MySavedFiles_ScrollViewController.refreshAll();
                            max_my.show();
                            break;
                        case 1:
                            documents_view_model.parameterForMashedUpCommunitiesAndFiles.key = null;
                            documents_max_Community_ScrollViewController.refreshAll();
                            max_com.show();
                            break;
                        case 2:
                            max_lib.show();
                            break;
                    }

                    documents_view_model.documents_max_mysavedfile_index.update();
                    documents_view_model.documents_max_community_index.update();

                    var isUp = documents_view_model.status_max_order[documents_view_model.status_max_panel_index].timeUp;
                    var order_time = $('#documents_menubar_orderbytime');
                    var order_name = $('#documents_menubar_orderbyname');
                    if (isUp) {
                        order_time.find("#documents_menubar_orderbytime_arrow_up")[0].style.display = 'block';
                        order_time.find("#documents_menubar_orderbytime_arrow_down")[0].style.display = 'none';
                    } else {
                        order_time.find("#documents_menubar_orderbytime_arrow_up")[0].style.display = 'none';
                        order_time.find("#documents_menubar_orderbytime_arrow_down")[0].style.display = 'block';
                    }
                    isUp = documents_view_model.status_max_order[documents_view_model.status_max_panel_index].nameUp;
                    if (isUp) {
                        order_name.find("#documents_menubar_orderbyname_arrow_up")[0].style.display = 'block';
                        order_name.find("#documents_menubar_orderbyname_arrow_down")[0].style.display = 'none';
                    } else {
                        order_name.find("#documents_menubar_orderbyname_arrow_up")[0].style.display = 'none';
                        order_name.find("#documents_menubar_orderbyname_arrow_down")[0].style.display = 'block';
                    }
                }
            }
        },
        onMinSearchButtonClicked : function () {
            HomePage_Scrollable.zoom(5);
            this.onMaxSearchButtonClicked();
        },
        onMaxSearchButtonClicked : function () {
            documents_max_Search_ScrollViewController.reinit();
            var searchbar = $("#documents_body_max_search");
            if (searchbar.css('display') == 'none') {
                searchbar.show();
                $('#documents_panel_max_search').find('div.slimScrollDiv').hide();

                $("#documents_search_time_from").kendoDatePicker();
                $("#documents_search_time_to").kendoDatePicker();
            } else {
                $("#documents_body_max").show();
                searchbar.hide();
            }
        },
        onBackToAllFromSearchClicked : function () {
            $("#documents_body_max").show();
            $("#documents_body_max_search").hide();
        },
        onMaxDocumentClicked : function (element) {
            if(FLAG) return;
            FLAG = true;
            /*do {
                if (element == undefined) {
                    return;
                }
                element = element.parentNode;
            } while ($(element).find(".documents_doc_id").length == 0);*/
            element = $(element);
            element.prop('onclick', null).off('click');
            element.prop('onmouseout', null).off('mouseout');
            var docID = element.find(".documents_doc_id")[0].innerHTML;
            var notificationId = element.find(".documents_notif_id")[0].innerHTML;
            var notificationType = element.find(".documents_notif_tp")[0].innerHTML;
            var communityId = element.find(".documents_com_id")[0].innerHTML;

            if (element.find('li').length > 3) {

            } else {
                documents_controller.requestDocumentDetail(element[0], docID,notificationId, notificationType, communityId);
            }
        },
        onMaxDocumentMouseOver : function(element) {
           /* do {
                if (element == undefined) {
                    return;
                }
                element = element.parentNode;
            } while ($(element).find(".documents_doc_id").length == 0);*/
            var menuArrow = $(element).find('.documents_panel_list_item_menuArrow')[0];
            $(menuArrow).show();
        },
        onMaxDocumentMouseOut : function(element) {
            var menuArrow = $(element).find('.documents_panel_list_item_menuArrow')[0];
            var menuList = $(element).find(".documents_panel_list_item_menulist_ul")[0];
            var mmenu = $(menuList).data('kendoMenu');
            if (mmenu) {
                mmenu.destroy();
            }
            $(element).off('click').click(function(e){
                e.stopPropagation();
                documents_controller.onMaxDocumentClicked(element);
            });
            $(menuList).empty().html('<li><p></p><ul></ul></li>');
            $(menuList).hide();
            $(menuArrow).hide();
        },
        onMaxDocumentMenuListClicked : function (e) {
            e.preventDefault();
            var element = e.item.parentNode;
            do {
                if (element == undefined) {
                    return;
                }
                element = element.parentNode;
            } while ($(element).find(".documents_doc_id").length == 0);

            var selectedItemText = e.item.textContent;
            switch (selectedItemText) {
                case 'Download':
                    window.open(documents_view_model.data_DocumentDetail.AttachmentUrl);
                    break;
                case 'Check-out':
                    documents_controller.requestCheckOut(false);
                    break;
                case 'Discard Check-out':
                    documents_controller.requestCheckOut(true);
                    break;
                case 'Check-in':
                    documents_view_model.documents_document_detail_win.data('kendoWindow').close();
                    documents_view_model.documents_checkin_win.data('kendoWindow').center();
                    documents_view_model.documents_checkin_win.data('kendoWindow').open();
                    break;
                case 'Properties':
                    documents_controller.updateDocumentDetailWindow();
                    documents_view_model.request_LikedPeople(function(){
                        kendo.bind($("#documents_document_details_windows"), documents_view_model);
                        loader.hide();
                    });
                    break;
                case 'Version History':
                    documents_controller.requestDocumentVersions();
                    break;
                case 'Copy' :
                    documents_controller.requestCopyToCommunityList();
                    break;
                default :
                    break;
            }
        },
        onMaxCommunityClicked : function (element) {
            do {
                if (element == undefined) {
                    return;
                }
                element = element.parentNode;
            } while ($(element).find(".documents_com_id").length == 0);
            var tableElement = $(element).find(".documents_com_id");
            var comID = tableElement[0].innerHTML;
            community_profile_controller.initProfilePage(comID);
        },
        onOrderbyTimeClicked : function(element) {
            var isUp = documents_view_model.status_max_order[documents_view_model.status_max_panel_index].timeUp;
            isUp = !isUp;
            documents_view_model.status_max_order[documents_view_model.status_max_panel_index].timeUp = isUp;
            if (isUp) {
                $(element).find("#documents_menubar_orderbytime_arrow_up")[0].style.display = 'block';
                $(element).find("#documents_menubar_orderbytime_arrow_down")[0].style.display = 'none';
            } else {
                $(element).find("#documents_menubar_orderbytime_arrow_up")[0].style.display = 'none';
                $(element).find("#documents_menubar_orderbytime_arrow_down")[0].style.display = 'block';
            }
            switch (documents_view_model.status_max_panel_index) {
                case 0://my saved files
                    documents_view_model.parameterForMySavedFiles.filter = 'Time';
                    documents_view_model.parameterForMySavedFiles.order = !isUp;
                    documents_max_MySavedFiles_ScrollViewController.refreshAll();
                    break;
                case 1:
                    documents_view_model.parameterForMashedUpCommunitiesAndFiles.filter = 'Time';
                    documents_view_model.parameterForMashedUpCommunitiesAndFiles.order = !isUp;
                    documents_max_Community_ScrollViewController.refreshAll();
                    break;
            }
        },
        onOrderbyNameClicked : function(element) {
            var isUp = documents_view_model.status_max_order[documents_view_model.status_max_panel_index].nameUp;
            isUp = !isUp;
            documents_view_model.status_max_order[documents_view_model.status_max_panel_index].nameUp = isUp;
            if (isUp) {
                $(element).find("#documents_menubar_orderbyname_arrow_up")[0].style.display = 'block';
                $(element).find("#documents_menubar_orderbyname_arrow_down")[0].style.display = 'none';
            } else {
                $(element).find("#documents_menubar_orderbyname_arrow_up")[0].style.display = 'none';
                $(element).find("#documents_menubar_orderbyname_arrow_down")[0].style.display = 'block';
            }
            switch (documents_view_model.status_max_panel_index) {
                case 0://my saved files
                    documents_view_model.parameterForMySavedFiles.filter = 'name';
                    documents_view_model.parameterForMySavedFiles.order = isUp;
                    documents_max_MySavedFiles_ScrollViewController.refreshAll();
                    break;
                case 1:
                    documents_view_model.parameterForMashedUpCommunitiesAndFiles.filter = 'name';
                    documents_view_model.parameterForMashedUpCommunitiesAndFiles.order = !isUp;
                    documents_max_Community_ScrollViewController.refreshAll();
                    break;
            }
        },
        onRestoreVersionClicked : function(element, version) {
            documents_controller.requestRestoreDocumentVersion(version);
        },
        onBrowseClicked : function(element) {

        },
        onUploadClicked : function(element) {
            var retMark = false;
            var types = ['jpeg','jpg','gif','bmp', 'png','tiff','tif','pdf','docx','doc','pptx','ppt','xlsx','xls','txt','zip'];
            if (!$('#documents_select_file').find('.k-file:last').data() || !$.trim($('#documents_select_file_name').val())) {
                var browseBtn = $('#documents_select_file');
                browseBtn.kendoTooltip({
                    content: 'Please select a file.',
                    position: "right",
                    showOn: false
                });
                browseBtn.data('kendoTooltip').show();
                retMark = true;
            }
            var remarksArea = $('#documents_select_file_remarks');
            if (!$.trim(remarksArea.val())) {
                remarksArea.kendoTooltip({
                    content: 'Please input the remarks text.',
                    position: "right",
                    showOn: false
                });
                remarksArea.data('kendoTooltip').show();
                retMark = true;
            }
            if (retMark) {
                return;
            }
            var fullFileName = $('#documents_select_file').find('.k-file:last').data().fileNames[0].name;
            var realFileName = documents_view_model.data_DocumentDetail.AttachmentUrl.replace(/^.*(\\|\/|\:)/, '');
            if (realFileName != fullFileName) {
                var browseBtn = $('#documents_select_file');
                browseBtn.kendoTooltip({
                    content: 'The uploaded document is different from the original one. Please check the document name.',
                    position: "right",
                    showOn: false
                });
                browseBtn.data('kendoTooltip').show();
                return;
            }
            var documentSelectedAttechment = $('#documents_select_file').find('.k-file:last').data().fileNames[0].rawFile;
            documents_view_model.documentSelectedFile.push(documentSelectedAttechment);
            var fileContent, fileSuffix;
            fileContent = new Object();
            fileContent.AttachmentName = documents_view_model.documentSelectedFile[0].name.substr(0, documents_view_model.documentSelectedFile[0].name.lastIndexOf("."));
            fileContent.Attachmentbytes = documents_view_model.documentSelectedFileContents[0];
            fileSuffix = documents_view_model.documentSelectedFile[0].name;
            fileSuffix = fileSuffix.substr(fileSuffix.lastIndexOf(".") + 1);
            $.inArray(fileSuffix, types) > -1 ? fileContent.AttachmentType = fileSuffix : null;
            documents_view_model.documentSelectedFile[0].type.match(/image.*/) ? documents_view_model.imageContents.push(fileContent) : documents_view_model.attachContents.push(fileContent);
            documents_controller.requestCheckIn();
        },
        onCopyClicked : function(element) {
            var input = $('#documents_copy_window_input');
            if (input.val() != documents_view_model.data_CopyCandidate.selected.Name || !documents_view_model.data_CopyCandidate.selected.ID) {
                input.kendoTooltip({
                    content: 'Please select an existing community',
                    position: "right",
                    showOn: false
                });
                input.data('kendoTooltip').show();
                return;
            }
            documents_controller.requestCopy();
        },
        onCopyInputChanged : function () {
            var input = $('#documents_copy_window_input').val();
            documents_controller.updateCopyCandidate(input);
        },
        onCopyCandidateClicked : function (element) {
            var id = $(element).find('.documents_copy_candidate_id')[0].textContent;
            var name = $(element).find('.documents_copy_candidate_name')[0].textContent;
            documents_view_model.data_CopyCandidate.selected.ID = id;
            documents_view_model.data_CopyCandidate.selected.Name = name;
            $('#documents_copy_window_input').val(name);
        },
        getItem : function (indexes, menu) {
            var itemIndexes = indexes.split(/[.,]/);
            var item = $(menu);
            if (itemIndexes[0] !== "") {
                for (var i = 0, len = itemIndexes.length; i < len; i++) {
                    item = item.children("li").eq(itemIndexes[i]);
                    if (i < len-1) {
                        item = item.find("ul:first");
                    }
                }
            }
            return item;
        },
        getTimeByLocalTimeZone : function(date) {
            var originalDate = new Date(date);
            var localOffset = originalDate.getTimezoneOffset() * 60000;
            var localDate = originalDate.getTime() - localOffset;
            return kendo.toString(new Date(localDate), 'g');
        },
        getDocumentsIconWithType : function (type, isLarge) {
            var smallIcons = {
                doc : 'main_documents_e_20_20',
                docx : 'main_documents_e_20_20',
                tif : 'main_documents_t_20_20',
                tiff :'main_documents_t_20_20',
                xls : 'main_documents_o_20_20',
                xlsx : 'main_documents_o_20_20',
                pdf : 'main_documents_f_20_20',
                txt : 'main_big_n_20_20',
                ppt : 'main_big_k_20_20',
                pptx : 'main_big_k_20_20',
                jpg : 'main_big_j_20_20',
                jpeg : 'main_big_j_20_20',
                png : 'main_big_j_20_20',
                gif :'main_big_j_20_20',
                bmp : 'main_big_j_20_20',
                // tiff : 'main_big_j_20_20',
                zip : 'main_big_m_20_20'
            };
            var largeIcons = {
                doc : 'main_big_b_40_40',
                docx : 'main_big_b_40_40',
                tif : 'main_big_t_40_40',
                tiff : 'main_big_t_40_40',
                xls : 'main_big_a_40_40',
                xlsx : 'main_big_a_40_40',
                pdf : 'main_big_c_40_40',
                txt : 'main_big_i_40_40',
                ppt : 'main_big_e_40_40',
                pptx : 'main_big_e_40_40',
                jpg : 'main_big_d_40_40',
                jpeg : 'main_big_d_40_40',
                png : 'main_big_d_40_40',
                gif :'main_big_d_40_40',
                bmp : 'main_big_d_40_40',
                // tiff : 'main_big_d_40_40',
                zip : 'main_big_h_40_40'
            };
            if (type == null && type == undefined) {
                if (isLarge) {
                    return largeIcons.doc;
                } else {
                    return smallIcons.doc;
                }
            }
            var lowerType = type.toLowerCase();
            var targetIconSet;
            if (isLarge) {
                targetIconSet = largeIcons;
            } else {
                targetIconSet = smallIcons;
            }
            var targetIcon = targetIconSet[lowerType];
            if (!targetIcon) {
                targetIcon = targetIconSet.doc;
            }
            return targetIcon;
        },
        updateCommunityDetailWindow : function () {
            kendo.bind($("#documents_community_details_windows"), documents_view_model);
        },
        updateDocumentDetailWindow : function () {
            var dwin = documents_view_model.documents_document_detail_win;
            // kendo.bind($("#documents_document_details_windows"), documents_view_model);
            dwin.data('kendoWindow').center();
            dwin.data('kendoWindow').open();
        },
        updateVersionDetailWindow : function () {
            var win = documents_view_model.documents_version_detail_win;
//          kendo.bind($('#documents_document_version_details_window'), documents_view_model);
            win.data('kendoWindow').center();
            win.data('kendoWindow').open();
        },
        updateDocumentMenuList :function(element, documentID) {
            var menuArrow = $(element).find('.documents_panel_list_item_menuArrow')[0];
            $(menuArrow).show();
            var menuList = $(element).find(".documents_panel_list_item_menulist_ul")[0];

            if(Workport.getBrowser() == 'ie10' || Workport.getBrowser() == 'ie11'){
                $(menuList).css({top:'-10px'});
            }
            $(menuList).show();
            menuList.style.zIndex = 1000;
            if ($(element).find('li').length > 3) {
                var mmenu = $(menuList).data('kendoMenu');
                if (mmenu) {
                    mmenu.destroy();
                }
                $(menuList).empty().html('<li><p></p><ul></ul></li>');
            } //else {
                var realMenu = $(menuList).kendoMenu({
                    hoverDelay: 200,
                    select: documents_controller.onMaxDocumentMenuListClicked,
                    close : function (e) {
                        FLAG = false;
                        $(menuArrow).hide();
                        $(element).on('mouseout',function(){
                            documents_controller.onMaxDocumentMouseOut(element);
                        });
                    }
                }).data('kendoMenu');
                $(menuList).find(".k-icon")[0].style.display = 'none';
            //}
            if (true) {
                realMenu.append({text: 'Download'}, this.getItem('0', menuList));
                if (documents_view_model.data_DocumentDetail.EnableCheckout == true) {
                    realMenu.append({text: 'Check-out'}, this.getItem('0', menuList));
                }
                if (documents_view_model.data_DocumentDetail.EnableCheckin == true) {
                    realMenu.append({text: 'Discard Check-out'}, this.getItem('0', menuList));
                    realMenu.append({text: 'Check-in'}, this.getItem('0', menuList));
                }
                realMenu.append({text: 'Properties'}, this.getItem('0', menuList));
                realMenu.append({text: 'Version History'}, this.getItem('0', menuList));
                realMenu.append({text: 'Copy'}, this.getItem('0', menuList));
            } else {
                realMenu.insertBefore({text: 'Copy'}, this.getItem('0', menuList));
                realMenu.insertBefore({text: 'Version History'}, this.getItem('0', menuList));
                realMenu.insertBefore({text: 'Properties'}, this.getItem('0', menuList));
                if (documents_view_model.data_DocumentDetail.EnableCheckin == true) {
                    realMenu.insertBefore({text: 'Discard Check-out'}, this.getItem('0', menuList));
                    realMenu.insertBefore({text: 'Check-in'}, this.getItem('0', menuList));
                }
                if (documents_view_model.data_DocumentDetail.EnableCheckout == true) {
                    realMenu.insertBefore({text: 'Check-out'}, this.getItem('0', menuList));
                }
                realMenu.insertBefore({text: 'Download'}, this.getItem('0', menuList));
            }
            //add id for auto test
            var ele = $(menuList).find('li');
            for (var i = 0; i < ele.length; i ++) {
                var text = ele[i].textContent.replace(/\s/g,"");
                $(ele[i]).attr('id', 'documents_docmenu_id_'+text);
            }

            realMenu.open(documents_controller.getItem('0', menuList));
            $(menuList).find(".k-icon")[0].style.display= 'none';
            $(menuList).find("span:first")[0].style.display= 'none';
        },
        updateCopyWindow :  function () {
            // var win = documents_view_model.documents_copy_win;
            // // kendo.bind($('#documents_document_copy_window'), documents_view_model);
            // win.data('kendoWindow').center();
            // win.data('kendoWindow').open();
            documents_controller.updateCopyCandidate('');
            $('#documents_copy_window_input').val('');
        },
        updateCopyCandidate : function(input) {
            documents_view_model.data_CopyCandidate.data.length = 0;
            if (documents_view_model.data_CopyToCommunityList == undefined) {
                return;
            }
            /*var selector = ['ModeratorCommunities','MemberCommunities'];
            for (var j = 0; j < selector.length; j ++) {
                var select = documents_view_model.data_CopyToCommunityList[selector[j]];
                if (select != undefined) {
                    for (var i = 0; i < select.length; i ++) {
                        var item = select[i];
                        if (item.Name != null) {
                            var lowName = item.Name.toLowerCase();
                            var lowInput = input.toLowerCase();
                            var index = lowName.indexOf(lowInput);
                            if (index >= 0) {
                                documents_view_model.data_CopyCandidate.data.push(item);
                            }
                        }
                    }
                }
            }*/
            var select = documents_view_model.data_CopyToCommunityList, item;
            for (var i = 0; i < select.length; i ++) {
                item = select[i];
                if (item.name != null) {
                    item.Name = item.name; item.ID = item.id;
                    var lowName = item.Name.toLowerCase();
                    var lowInput = input.toLowerCase();
                    var index = lowName.indexOf(lowInput);
                    if (index >= 0) {
                        documents_view_model.data_CopyCandidate.data.push(item);
                    }
                }
            }
            kendo.bind($('#documents_copy_window_candidate_area'),documents_view_model);
        },
        requestDocumentDetail : function(menuElement, documentID,nId, nType, tId) {
            var callback = function (iuccess) {
                documents_controller.updateDocumentMenuList(menuElement, documentID);
            };
            documents_view_model.request_DocumentDetail(menuElement, documentID,nId, nType, tId, callback);
        },
        requestCheckOut : function(isDiscardCheckOut){
            var callback = function () {
                if (isDiscardCheckOut == false) {
                    window.open(documents_view_model.data_DocumentDetail.AttachmentUrl);
                }
            };
            documents_view_model.request_Checkout(isDiscardCheckOut, callback);
        },
        requestCheckIn : function () {
            var callback = function () {
                $('#documents_select_file_name').val('');
                $('#documents_select_file_remarks').val('');
                documents_view_model.documents_checkin_win.data('kendoWindow').close();
            };
            var comments = $('#documents_select_file_remarks').val();
            var version = $('input[name="upload_type"]:checked').val();
            documents_view_model.request_Checkin((version=='major'?'1':'0'), comments, callback);
        },
        requestDocumentVersions : function () {
            documents_controller.updateVersionDetailWindow();
            var cb = function () {
                kendo.bind($('#documents_document_version_details_window'), documents_view_model);
                loader.hide();
            };
            documents_view_model.request_DocumentVersionDetails(cb);
        },
        requestRestoreDocumentVersion : function (version) {
            var cb = function () {
                var win = documents_view_model.documents_version_detail_win;
                win.data('kendoWindow').close();
            };
            documents_view_model.request_RestoreDocumentVersion(cb, version);
        },
        requestCopyToCommunityList : function () {
            var win = documents_view_model.documents_copy_win;
            win.data('kendoWindow').center();
            win.data('kendoWindow').open();
            win.find('ul').off('*').empty();
            var cb = function () {
                documents_controller.updateCopyWindow();
                kendo.bind($('#documents_document_copy_window'), documents_view_model);
                loader.hide();
            };
            documents_view_model.request_CopyToCommunityList(cb);
        },
        requestCopy : function () {
            loader.show();
            var cb = function () {
                documents_view_model.documents_copy_win.data('kendoWindow').close();
                loader.hide();
            };
            documents_view_model.request_Copy(cb);
        }
    }
})();

var documents_view_model = kendo.observable({
    //data (response of server)
    //data for the scroll views
    data_MySavedFiles : {
        data: [],
        respCode : ''
    },
    data_CommunitiesFiles : {
        data : [],
        respCode : ''
    },
    data_LibraryTools : {
        data : []
    },
    menuItems : {
        data : [
            "My Documents", "My Communities"//, "Library Tools"
        ]
    },
    search_result : {
        keyword : '',
        data : [],
        respCode : ''
    },
    //data for community detail win
    data_CommunityDetail : {},
    //data for document detail win
    data_DocumentDetail : {},
    //data for copy candidate
    data_CopyToCommunityList : {},//all data
    data_CopyCandidate : {selected:{}, data:[]},//display candidates

    //status data
    status_min_display : true,
    status_max_panel_index : 0,//0:my saved file; 1:community; 2:library tools.
    status_max_order : [{timeUp : true, nameUp : true, modifieyUp : true},{timeUp : true, nameUp : true, modifieyUp : true},{timeUp : true, nameUp : true, modifieyUp : true}],

    //views
    documents_community_detail_win : {},
    documents_document_detail_win : {},
    documents_version_detail_win : {},
    documents_checkin_win : {},
    documents_copy_win : {},
    //documents_full_screen_loading_layer : {},

    //a-z index
    documents_min_mysavedfile_index : {},
    documents_max_mysavedfile_index : {},
    documents_max_community_index : {},

    //networks array(for the async network later)
    requestArray : [],
    callbackArray : [],
    availableArray : [],

    //check-in
    documentSelectedFile:[],
    documentSelectedFileContents:[],
    attachContents: [],
    imageContents: [],

    //networks ||||| below
    parameterForMySavedFiles : {
        _type : 'mysavedfiles',
        pageSize : '51',
        offset : null,
        order : false,// false = descending order/ true = ascending order
        filter : null,//Name, Modified by
        key : null
    },
    scrollTop_MySavedFiles : 0,
    firstTime : true,
    lastReq:null,
    request_MySavedFiles : function (isMore, controllerCB, scrollTop) {
        var parameter;
        if (isMore) {
            var offset = '';
            var dataLength = documents_view_model.data_MySavedFiles.data.length - 1;
            if (isMore > 0) {
                if (dataLength >= 0) {
                    offset = documents_view_model.data_MySavedFiles.data[dataLength].PagePosition;
                }
                parameter = {
                    _type : this.parameterForMySavedFiles._type,
                    pageSize : this.parameterForMySavedFiles.pageSize,
                    order : this.parameterForMySavedFiles.order,
                    filter : this.parameterForMySavedFiles.filter,
                    offset : offset,
                    key : this.parameterForMySavedFiles.key
                };
                if (documents_view_model.data_MySavedFiles.respCode == 'WP1005') {
                    documents_min_MySavedFiles_ScrollViewController.loader.hide();
                    return false;
                }
                if (this.scrollTop_MySavedFiles == scrollTop) {
                    documents_min_MySavedFiles_ScrollViewController.loader.hide();
                    return false;
                }
            } else if (isMore < 0) {
                if (dataLength >= 0) {
                    offset = documents_view_model.data_MySavedFiles.data[0].PagePosition;
                }
                parameter = {
                    _type : this.parameterForMySavedFiles._type,
                    pageSize : this.parameterForMySavedFiles.pageSize,
                    order : !this.parameterForMySavedFiles.order,
                    filter : this.parameterForMySavedFiles.filter,
                    offset : offset,
                    key : this.parameterForMySavedFiles.key
                };
            }
        }else {
            parameter = {
                _type : this.parameterForMySavedFiles._type,
                pageSize : this.parameterForMySavedFiles.pageSize,
                order : this.parameterForMySavedFiles.order,
                filter : this.parameterForMySavedFiles.filter,
                offset : null,
                key : this.parameterForMySavedFiles.key
            }
        }
        this.scrollTop_MySavedFiles = scrollTop;
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);
        var cb = function (data) {
            documents_min_MySavedFiles_ScrollViewController.loader.hide();
            var index = $.inArray(req, documents_view_model.requestArray);
            if (index >= 0) {
                var avail = documents_view_model.availableArray[index];
                while (avail) {
                    if (!data || !data.FileBasicDetails) {
                        if (isMore == 0) {
                            documents_view_model.data_MySavedFiles.data.length = 0;
                        }
                        var realCB = documents_view_model.callbackArray[index];
                        realCB(null);
                        break;
                    }

                    documents_view_model.data_MySavedFiles.respCode = data.ResponseCode;
                    if (isMore == 0) {
                        documents_view_model.data_MySavedFiles.data.length = 0;
                        documents_view_model.data_MySavedFiles.data = data.FileBasicDetails;
                    } else if (isMore > 0) {
                        documents_view_model.data_MySavedFiles.data = documents_view_model.data_MySavedFiles.data.concat(data.FileBasicDetails);
                    } else {
                        documents_view_model.data_MySavedFiles.data = data.FileBasicDetails.concat(documents_view_model.data_MySavedFiles.data);
                    }

                    var realCB = documents_view_model.callbackArray[index];
                    realCB(data.FileBasicDetails);

                    if (documents_view_model.firstTime) {
                        documents_view_model.firstTime = false;
                        documents_view_model.documents_min_mysavedfile_index.update();
                        setAppCount();
                    }

                    break;
                }

                documents_view_model.requestArray.splice(index, 1);
                documents_view_model.callbackArray.splice(index, 1);
                documents_view_model.availableArray.splice(index, 1);
            }
        };

        Workport.DocumentAPI.getSelf(cb, parameter);
        return true;
    },
    parameterForMashedUpCommunitiesAndFiles : {
        _type : 'mashedup',
        pageSize : 10,
        sinceid : 0,//rowNo
        order : false,
        filter : 'Time',//Name|Time
        key : ''//
    },
    scrollTop_CommunitiesAndFiles : 0,
    request_MashedUpCommunitiesAndFiles : function (isMore, controllerCB, scrollTop) {
        if (isMore) {
            if (documents_view_model.data_CommunitiesFiles.respCode == 'WP1005') {
                documents_min_MySavedFiles_ScrollViewController.loader.hide();
                return false;
            }
            if (this.scrollTop_CommunitiesAndFiles == scrollTop) {
                return false;
            }
            if (isMore > 0) {
                var lastRow = 0;
                var dataLength = documents_view_model.data_CommunitiesFiles.data.length - 1;
                if (dataLength >= 0) {
                    lastRow = documents_view_model.data_CommunitiesFiles.data[dataLength].RowNo;
                }
                documents_view_model.parameterForMashedUpCommunitiesAndFiles.sinceid = lastRow;
            } else if (isMore < 0) {
                var lastRow = 0;
                var dataLength = documents_view_model.data_CommunitiesFiles.data.length - 1;
                if (dataLength >= 0) {
                    lastRow = documents_view_model.data_CommunitiesFiles.data[0].RowNo;
                }
                documents_view_model.parameterForMashedUpCommunitiesAndFiles.sinceid = lastRow;
            }
        } else {
            this.parameterForMashedUpCommunitiesAndFiles.sinceid = 0;
        }
        this.scrollTop_CommunitiesAndFiles = scrollTop;
        var parameter = this.parameterForMashedUpCommunitiesAndFiles;
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);
        var cb = function (data) {
            documents_view_model.data_CommunitiesFiles.respCode = data.ResponseCode;
            var index = $.inArray(req, documents_view_model.requestArray);
            if (index >= 0) {
                var avail = documents_view_model.availableArray[index];
                while (avail) {
                    if (!data) {
                        break;
                    }
                    if (!data.CommunityDocuments) {
                        if (!isMore) {
                            documents_view_model.data_CommunitiesFiles.data.length = 0;
                        }
                        var realCB = documents_view_model.callbackArray[index];
                        realCB(null);
                        break;
                    }
                    documents_view_model.data_CommunitiesFiles.respCode = data.ResponseCode;
                    if (isMore == 0) {
                        documents_view_model.data_CommunitiesFiles.data.length = 0;
                        documents_view_model.data_CommunitiesFiles.data = data.CommunityDocuments;
                    } else if (isMore > 0) {
                        documents_view_model.data_CommunitiesFiles.data = documents_view_model.data_CommunitiesFiles.data.concat(data.CommunityDocuments);
                    } else if (isMore < 0) {
                        documents_view_model.data_CommunitiesFiles.data = data.CommunityDocuments.concat(documents_view_model.data_CommunitiesFiles.data);
                    }

                    var realCB = documents_view_model.callbackArray[index];
                    realCB(data.CommunityDocuments);
                    break;
                }
                documents_view_model.requestArray.splice(index, 1);
                documents_view_model.callbackArray.splice(index, 1);
                documents_view_model.availableArray.splice(index, 1);
            }
        };
        Workport.DocumentAPI.getAll(cb,parameter);
        return true;
    },
    parameterForCommunityDocs : {
        communityId : '',
        pageSize : 36,
        offset : ''//(Lastmodifieddate of the last record)
    },
    request_CommunityDocs : function (communityID, isMore, controllerCB) {
        var parameter = this.parameterForCommunityDocs;
        parameter.communityId = communityID;
        var targetCommunity;
        for (var i = 0; i < this.data_CommunitiesFiles.data.length; i ++) {
            var tempComm = this.data_CommunitiesFiles.data[i];
            if (tempComm.CommunityId == communityID) {
                targetCommunity = tempComm;
                break;
            }
        }
        if (targetCommunity == undefined) {
            return;
        }
        if (targetCommunity.respCode) {
            if (isMore && targetCommunity.respCode == 'WP1005') {
                return;
            }
        }
        targetCommunity.respCode = '';

        if (isMore) {
            var lastIndex = targetCommunity.FileBasicDetails.length - 1;
            if (lastIndex >= 0) {
                parameter.offset = targetCommunity.FileBasicDetails[lastIndex].LastModifiedDate;
            }
        } else {
            parameter.offset = '';
        }

        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);

        var cb = function (data) {
            var index = $.inArray(req, documents_view_model.requestArray);
            if (index >= 0) {
                var avail = documents_view_model.availableArray[index];
                while (avail) {
                    if (!data) {
                        break;
                    }
                    targetCommunity.respCode = data.ResponseCode;
                    if (!data.FileBasicDetails) {
                        Workport.utils.alertMsg("", data.ResponseMessage, function(_data){});
                        break;
                    }

                    if (isMore) {
                        if (targetCommunity.FileBasicDetails.length == 0) {
                            targetCommunity.FileBasicDetails = data.FileBasicDetails;
                        } else {
                            targetCommunity.FileBasicDetails = targetCommunity.FileBasicDetails.concat(data.FileBasicDetails);
                        }
                    } else {
                        targetCommunity.FileBasicDetails = data.FileBasicDetails;
                    }

                    var realCB = documents_view_model.callbackArray[index];
                    realCB(data.FileBasicDetails);
                    break;
                }

                documents_view_model.requestArray.splice(index, 1);
                documents_view_model.callbackArray.splice(index, 1);
                documents_view_model.availableArray.splice(index, 1);
            }
        };
        Workport.DocumentAPI.getCommunity(cb,parameter);
    },

    parameterForDocumentDetail : {
        documentId : '',
        type : '',
        targetId : '',
        notificationId : '',
        communityId : ''
    },
    request_DocumentDetail : function (menuElement, documentID,nId, nType, tId, controllerCB) {
        var comId = tId;
        if (nType == 'U' || nType == 'u') {
            var userId = WP_USER_ID.toString();
            var index = userId.indexOf('\\');
            if (index > 0) {
                userId = userId.slice(index+1);
            }
            tId = userId;//WP_USER_ID = "MWP\CA160590"
        }
        var parameter = {
            documentId:documentID,
            type: nType,
            targetId: tId
        };
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);

        documents_min_MySavedFiles_ScrollViewController.loader.setOptions({imgColor:'black', textCSS:{'color':'black'},boxCSS:{'opacity':1}});
        documents_min_MySavedFiles_ScrollViewController.loader.show();

        var cb = function(data) {
            documents_min_MySavedFiles_ScrollViewController.loader.hide();

            var index = $.inArray(req, documents_view_model.requestArray);
            if (index >= 0) {
                var avail = documents_view_model.availableArray[index];
                while (avail) {
                    if (!data) {
                        documents_controller.FLAG = false;
                        documents_controller.onMaxDocumentMouseOut(menuElement);
                        $(menuElement).on('mouseout',function(){
                            documents_controller.onMaxDocumentMouseOut(this);
                        });
                        break;
                    }
                    if (!data.Documents) {
                        documents_controller.FLAG = false;
                        Workport.utils.alertMsg("", data.ResponseMessage, function(_data){});
                        documents_controller.onMaxDocumentMouseOut(menuElement);
                        $(menuElement).on('mouseout',function(){
                            documents_controller.onMaxDocumentMouseOut(this);
                        });
                        break;
                    }
                    documents_view_model.parameterForDocumentDetail.documentId = documentID;
                    documents_view_model.parameterForDocumentDetail.type = nType;
                    documents_view_model.parameterForDocumentDetail.targetId = tId;
                    documents_view_model.parameterForDocumentDetail.notificationId = nId;
                    documents_view_model.parameterForDocumentDetail.communityId = comId;
                    documents_view_model.data_DocumentDetail = data.Documents[0];
                    documents_view_model.data_DocumentDetail.docID = documentID;

                    var realCB = documents_view_model.callbackArray[index];
                    realCB();
                    break;
                }

                documents_view_model.requestArray.splice(index, 1);
                documents_view_model.callbackArray.splice(index, 1);
                documents_view_model.availableArray.splice(index, 1);
            }
        };
        Workport.DocumentAPI.getDetail(cb, parameter);
    },
    request_LikedPeople : function(controllerCB) {
        var parameter = {
            targetId : documents_view_model.parameterForDocumentDetail.notificationId,
            pageSize : 10,
            pageNumber : 0
        };
        documents_view_model.data_DocumentDetail.LikedUsersDetails = [];

        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);

        var cb = function(data) {
            var index = $.inArray(req, documents_view_model.requestArray);
            if (index >= 0) {
                var avail = documents_view_model.availableArray[index];
                while (avail) {
                    if (!data) {
                        break;
                    }
                    if (!data.LikedUsersDetails) {
                        break;
                    }
                    documents_view_model.data_DocumentDetail.LikedUsersDetails = data.LikedUsersDetails;
                    break;
                }
                var realCB = documents_view_model.callbackArray[index];
                realCB();
                documents_view_model.requestArray.splice(index, 1);
                documents_view_model.callbackArray.splice(index, 1);
                documents_view_model.availableArray.splice(index, 1);
            }
        };
        Workport.StreamAPI.getLikeByNotify(cb, parameter);
    },
    request_Checkout : function(isDiscard, controllerCB) {
        var parameter = {
            notificationId : documents_view_model.parameterForDocumentDetail.notificationId,
            notificationType : documents_view_model.parameterForDocumentDetail.type,
            documentId : documents_view_model.parameterForDocumentDetail.documentId,
            targetId : documents_view_model.parameterForDocumentDetail.targetId
        };
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);

        var cb = function(data) {
            var index = $.inArray(req, documents_view_model.requestArray);
            if (index >= 0) {
                var avail = documents_view_model.availableArray[index];
                while (avail) {
                    if (!data) {
                        break;
                    }
                    if (data.ResponseCode != 'WP1008') {
                        Workport.utils.alertMsg("", data.ResponseMessage, function (_data) {
                        });
                        break;
                    }
                    var realCB = documents_view_model.callbackArray[index];
                    realCB();
                    break;
                }

                documents_view_model.requestArray.splice(index, 1);
                documents_view_model.callbackArray.splice(index, 1);
                documents_view_model.availableArray.splice(index, 1);
            }
        };
        if (isDiscard) {
            Workport.DocumentAPI.discard(cb, parameter);
        } else {
            Workport.DocumentAPI.checkout(cb, parameter);
        }
    },

    request_Checkin : function (version, comments, controllerCB) {
        var parameter = {
            notificationId : documents_view_model.parameterForDocumentDetail.notificationId,
            notificationType: documents_view_model.parameterForDocumentDetail.type,
            documentId: documents_view_model.parameterForDocumentDetail.documentId,
            targetId: documents_view_model.parameterForDocumentDetail.targetId,
            version: version,
            comments: comments,
            documentContent: documents_view_model.documentSelectedFileContents[0]
        };
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);

        var cb = function(data) {
            var index = $.inArray(req, documents_view_model.requestArray);
            if (index >= 0) {
                var avail = documents_view_model.availableArray[index];
                while (avail) {
                    if (!data) {
                        break;
                    }
                    if (data.ResponseCode != 'WP1008') {
                        Workport.utils.alertMsg("", data.ResponseMessage, function (_data) { });
                    }
                    var realCB = documents_view_model.callbackArray[index];
                    documents_view_model.documentSelectedFileContents.length = 0;
                    documents_view_model.documentSelectedFile.length = 0;
                    realCB();
                    break;
                }

                documents_view_model.requestArray.splice(index, 1);
                documents_view_model.callbackArray.splice(index, 1);
                documents_view_model.availableArray.splice(index, 1);
            }
        };
        Workport.DocumentAPI.checkin(cb, parameter);
    },

    parameterForSearch : {
        pageSize : 48,
        entity : 'U',//U:MySavedFiles/C:Community
        key : '',
        offset: ''
    },
    scrollTop_Search : 0,
    request_Search : function(isMore, keyword, controllerCB, scrollTop) {
        if (isMore) {
            if (this.scrollTop_Search == scrollTop) {
                return false;
            }
            if (documents_view_model.search_result.respCode == 'WP1005') {
                return false;
            }
            var dataLength = documents_view_model.search_result.data.length - 1;
            if (dataLength >= 0) {
                var lastData = documents_view_model.search_result.data[dataLength].LastModifiedDate;
                documents_view_model.parameterForSearch.offset = lastData;
            }
        } else {
            this.parameterForSearch.offset = '';
            this.parameterForSearch.key = $.param({key:keyword}).substring(4);
        }
        this.scrollTop_Search = scrollTop;
        var parameter = this.parameterForSearch;
        var req = JSON.stringify(parameter);
        if(this.lastReq == req){
            return false;
        }
        this.lastReq = req;
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);
        var cb = function (data) {
            var index = $.inArray(req, documents_view_model.requestArray);
            if (index >= 0) {
                var avail = documents_view_model.availableArray[index];
                while (avail) {
                    if (!isMore) {
                        documents_view_model.search_result.keyword = keyword;
                        documents_view_model.search_result.data.length = 0;
                    }
                    if($.trim(data.ResponseMessage) == "Request failed"){
                        Workport.utils.alertMsg("", data.ResponseMessage, function (_data) { });
                        break;
                    }
                    if (!data || !data.SearchBasicDetails) {
                        var realCB = documents_view_model.callbackArray[index];
                        realCB(null);
                        break;
                    }
                    documents_view_model.search_result.respCode = data.ResponseCode;
                    if (documents_view_model.search_result.data.length == 0) {
                        documents_view_model.search_result.data = data.SearchBasicDetails;
                    } else {
                        documents_view_model.search_result.data = documents_view_model.search_result.data.concat(data.SearchBasicDetails);
                    }

                    var realCB = documents_view_model.callbackArray[index];
                    data.SearchBasicDetails.keyword = documents_view_model.search_result.keyword;
                    realCB(data.SearchBasicDetails);
                    break;
                }


                documents_view_model.requestArray.splice(index, 1);
                documents_view_model.callbackArray.splice(index, 1);
                documents_view_model.availableArray.splice(index, 1);
            }
        };
        Workport.DocumentAPI.search(cb,parameter);
        return true;
    },
    request_DocumentVersionDetails : function (controllerCB) {
        var parameter = {
            type : documents_view_model.parameterForDocumentDetail.type,
            targetId : documents_view_model.parameterForDocumentDetail.targetId,
            documentId : documents_view_model.parameterForDocumentDetail.documentId
        };
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);

        var cb = function(data) {
            var index = $.inArray(req, documents_view_model.requestArray);
            if (index >= 0) {
                var avail = documents_view_model.availableArray[index];
                while (avail) {
                    if (!data) {
                        break;
                    }

                    if (!data.Versions) {
                        Workport.utils.alertMsg("", data.ResponseMessage, function (_data) { });
                        break;
                    }
                    documents_view_model.data_DocumentDetail.versions = data.Versions;

                    var realCB = documents_view_model.callbackArray[index];
                    realCB();
                    break;
                }

                documents_view_model.requestArray.splice(index, 1);
                documents_view_model.callbackArray.splice(index, 1);
                documents_view_model.availableArray.splice(index, 1);
            }
        };
        Workport.DocumentAPI.getVersion(cb, parameter);
    },
    request_RestoreDocumentVersion : function (controllerCB, version) {
        var parameter = {
            documentId : documents_view_model.parameterForDocumentDetail.documentId,
            version : version,
            type : documents_view_model.parameterForDocumentDetail.type,
            targetId : documents_view_model.parameterForDocumentDetail.targetId
        };
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);

        var cb = function(data) {
            var index = $.inArray(req, documents_view_model.requestArray);
            if (index >= 0) {
                var avail = documents_view_model.availableArray[index];
                while (avail) {
                    if (!data) {
                        break;
                    }
                    if (data.ResponseCode != 'WP1008') {
                        Workport.utils.alertMsg("", data.ResponseMessage, function (_data) { });
                    }
                    var realCB = documents_view_model.callbackArray[index];
                    realCB();
                    break;
                }

                documents_view_model.requestArray.splice(index, 1);
                documents_view_model.callbackArray.splice(index, 1);
                documents_view_model.availableArray.splice(index, 1);
            }
        };
        Workport.DocumentAPI.restore(cb, parameter);
    },
    request_CopyToCommunityList : function (controllerCB) {
        var parameter = {
            remark : 'CopyCommunityList'
        };
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);

        var cb = function(data) {
            documents_controller.loader.hide();
            var index = $.inArray(req, documents_view_model.requestArray);
            if (index >= 0) {
                var avail = documents_view_model.availableArray[index];
                while (avail) {
                    /*if (!data) {break; }
                    if (!data.UserAccessDetailsModel) {Workport.utils.alertMsg("", data.ResponseMessage, function (_data) { }); }
                    documents_view_model.data_CopyToCommunityList = data.UserAccessDetailsModel[0];*/
                    documents_view_model.data_CopyToCommunityList = WP_COMMUNITY_LIST;
                    var realCB = documents_view_model.callbackArray[index];
                    realCB();
                    break;
                }
                documents_view_model.requestArray.splice(index, 1);
                documents_view_model.callbackArray.splice(index, 1);
                documents_view_model.availableArray.splice(index, 1);
            }
        };
        cb();
        // Workport.UserAPI.getAccessUser(cb);
    },

    parameterForCopy : {
        targetId : '',
        tags : '',
        entityId : '',
        entityType : '',
        communityId : '',
        attachmentName : null,
        attachmentType : null,
        attachmentContent : null
    },
    parameterForCopyTo : { // for the new api copyto
        src : '',
        dest : '',
        documentId : '',
        type : ''
    },
    request_Copy : function (controllerCB){
//        documents_view_model.parameterForCopy.targetId = documents_view_model.data_CopyCandidate.selected.ID;
//        documents_view_model.parameterForCopy.entityType = documents_view_model.data_DocumentDetail.FileType;
//        documents_view_model.parameterForCopy.entityId = documents_view_model.parameterForDocumentDetail.documentId;
//        documents_view_model.parameterForCopy.communityId = documents_view_model.parameterForDocumentDetail.targetId;
        var newApiCopyTo = true;
        if (newApiCopyTo) {
            documents_view_model.parameterForCopyTo.dest = documents_view_model.data_CopyCandidate.selected.ID;
            documents_view_model.parameterForCopyTo.documentId = documents_view_model.parameterForDocumentDetail.documentId;
            documents_view_model.parameterForCopyTo.type = documents_view_model.parameterForDocumentDetail.type;
            documents_view_model.parameterForCopyTo.src = documents_view_model.parameterForDocumentDetail.targetId;
            var parameter = documents_view_model.parameterForCopyTo;
        } else {
            documents_view_model.parameterForCopy.targetId = documents_view_model.data_CopyCandidate.selected.ID;
            documents_view_model.parameterForCopy.entityType = documents_view_model.parameterForDocumentDetail.type;
            documents_view_model.parameterForCopy.entityId = documents_view_model.parameterForDocumentDetail.notificationId;
            documents_view_model.parameterForCopy.communityId = documents_view_model.parameterForDocumentDetail.communityId;
            documents_view_model.parameterForCopy.attachmentContent = null;
            var parameter = documents_view_model.parameterForCopy;
        }
        var req = JSON.stringify(parameter);
        this.requestArray.push(req);
        this.availableArray.push(true);
        this.callbackArray.push(controllerCB);

        var cb = function(data) {
            var index = $.inArray(req, documents_view_model.requestArray);
            if (index >= 0) {
                var avail = documents_view_model.availableArray[index];
                while (avail) {
                    if (!data) {
                        break;
                    }
                    if (data.ResponseCode != 'WP1008') {
                        Workport.utils.alertMsg("", data.ResponseMessage, function (_data) { });
                    }
                    var realCB = documents_view_model.callbackArray[index];
                    Workport.utils.alertMsg("", 'The document ' + documents_view_model.data_DocumentDetail.FileName + '.'+ documents_view_model.data_DocumentDetail.FileType  +' has been copied successfully to '+
                        documents_view_model.data_CopyCandidate.selected.Name +'.', function (_data) { });
                    realCB();
                    break;
                }

                documents_view_model.requestArray.splice(index, 1);
                documents_view_model.callbackArray.splice(index, 1);
                documents_view_model.availableArray.splice(index, 1);

            }
        };
        if (newApiCopyTo) {
            Workport.DocumentAPI.copyto(cb, parameter);
        } else {
            Workport.DocumentAPI.copy(cb, parameter);
        }
    }
});

$(function () {

    var width = $(window).width();
    var height = Screen.bodyHeight;
    $('#documents_panel').css({
        width:"256",
        height:height
    });

    //scroll in homepage
    HomePage_Scrollable.registerZoomCallback(5, documents_controller.zoomin_callback, documents_controller.zoomout_callback);
    $('.documents_panel_resize').bind( {
        click : function (e) {
            HomePage_Scrollable.zoom(5);
        }
    });

    //init documents view
    documents_controller.init();
    //load min panel
    documents_controller.load_minpage();
});